package com.rex.saas.controller;

import com.rex.saas.bean.BaseResponse;
import com.rex.saas.bean.ResultCode;
import com.rex.saas.bean.request.LabelAddRequest;
import com.rex.saas.bean.request.LabelDeleteRequest;
import com.rex.saas.bean.response.DeviceLabelResponse;
import com.rex.saas.bean.response.LabelResponse;
import com.rex.saas.constants.Constants;
import com.rex.saas.db.entity.SaasDeviceLabel;
import com.rex.saas.db.entity.SaasDeviceLabelRelation;
import com.rex.saas.db.entity.SaasSpaceLabel;
import com.rex.saas.service.LabelService;
import com.rex.saas.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@RestController
@Slf4j
@RequestMapping("/label")
public class LabelController {
    @Autowired
    private LabelService labelService;
    @GetMapping("/all")
    public BaseResponse all(HttpServletRequest request){
        String token = request.getHeader("token");
        String customerId = JwtUtils.getCustomerId(token);
        return BaseResponse.ok(labelService.queryAll(customerId));
    }
    @GetMapping("/custom")
    public BaseResponse custom(HttpServletRequest request){
        String token = request.getHeader("token");
        String customerId = JwtUtils.getCustomerId(token);
        return BaseResponse.ok(labelService.queryCustomLabels(customerId));
    }
    @GetMapping("/spaces")
    public BaseResponse spaces(HttpServletRequest request){
        String token = request.getHeader("token");
        String customerId = JwtUtils.getCustomerId(token);
        List<SaasSpaceLabel> spaceLabels = labelService.querySpaceLabels(customerId);
        if(CollectionUtils.isEmpty(spaceLabels)){
            log.error("querySpaceLabels spaceLabels is null, customerId:{}", customerId);
            return BaseResponse.error("空间标签不存在", ResultCode.PARAM_ERROR);
        }
        List<LabelResponse> responseList = new ArrayList<>();
        for (SaasSpaceLabel spaceLabel : spaceLabels){
            LabelResponse labelResponse = new LabelResponse();
            BeanUtils.copyProperties(spaceLabel, labelResponse);
            responseList.add(labelResponse);
        }
        return BaseResponse.ok(responseList);
    }
    @GetMapping("/devices")
    public BaseResponse devices(HttpServletRequest request, @RequestParam Long spaceLabelId){
        log.info("devices spaceLabelId:{}", spaceLabelId);
        String token = request.getHeader("token");
        String customerId = JwtUtils.getCustomerId(token);
        SaasSpaceLabel spaceLabel = labelService.getSpaceLabelById(spaceLabelId);
        if(spaceLabel==null){
            log.error("querySpaceLabels spaceLabel is null, spaceLabelId:{}", spaceLabelId);
            return BaseResponse.error("空间标签不存在", ResultCode.PARAM_ERROR);
        }
        if(spaceLabel.getCustomerId()!=null && !spaceLabel.getCustomerId().equals(customerId)){
            log.error("querySpaceLabels spaceLabel customerId not match error, spaceLabelId:{}", spaceLabelId);
            return BaseResponse.error("空间标签不存在", ResultCode.PARAM_ERROR);
        }
        List<SaasDeviceLabel> deviceLabels = labelService.queryDeviceLabelId(spaceLabelId);
        if(CollectionUtils.isEmpty(deviceLabels)){
            log.error("queryDeviceLabelId spaceLabels is null, spaceLabelId:{}", spaceLabelId);
            return BaseResponse.error("设备标签不存在", ResultCode.PARAM_ERROR);
        }
        List<DeviceLabelResponse> responseList = new ArrayList<>();
        for (SaasDeviceLabel deviceLabel : deviceLabels){
            if(!StringUtils.isEmpty(deviceLabel.getCustomerId()) && !deviceLabel.getCustomerId().equals(customerId)){
                continue;
            }
            DeviceLabelResponse deviceLabelResponse = new DeviceLabelResponse();
            BeanUtils.copyProperties(deviceLabel, deviceLabelResponse);
            deviceLabelResponse.setDeviceLabelId(deviceLabel.getId());
            deviceLabelResponse.setSpaceLabelId(spaceLabelId);
            deviceLabelResponse.setDeviceIconUrl(deviceLabel.getIconUrl());
            responseList.add(deviceLabelResponse);
        }
        return BaseResponse.ok(responseList);
    }
    @PostMapping("/addDefault")
    public BaseResponse addDefault(HttpServletRequest request,  @RequestBody LabelAddRequest labelAddRequest){
        log.info("addDefault:{}", labelAddRequest);
        String token = request.getHeader("token");
        String customerId = JwtUtils.getCustomerId(token);
        if(StringUtils.isEmpty(labelAddRequest.getLabelName())){
            log.error("addDefault labelName is null, labelAddRequest:{}", labelAddRequest);
            return BaseResponse.error("标签名称不能为空", ResultCode.PARAM_ERROR);
        }

        if(labelAddRequest.getType()==null) {
            log.error("addDefault type is null, labelAddRequest:{}", labelAddRequest);
            return BaseResponse.error("标签类型不能为空", ResultCode.PARAM_ERROR);
        }
        List<String> roles = JwtUtils.getRole(token);
        if (!roles.contains(Constants.SYSTEM_ADMIN)){
            log.error("addDefault no permission, labelAddRequest:{}", labelAddRequest);
            return BaseResponse.error("没有权限", ResultCode.PARAM_ERROR);
        }
        if(labelAddRequest.getType()==2){
            if(labelAddRequest.getSpaceLabelId()==null){
                log.error("addDefault spaceLabelId is null, labelAddRequest:{}", labelAddRequest);
                return BaseResponse.error("空间标签id不能为空", ResultCode.PARAM_ERROR);
            }
            SaasDeviceLabel saasDeviceLabel = labelService.queryDefaultDeviceLabelByName(labelAddRequest.getLabelName(), labelAddRequest.getSpaceLabelId());
            if(saasDeviceLabel!=null){
                log.error("addDefault device labelName is exist, labelAddRequest:{}", labelAddRequest);
                return BaseResponse.error("标签名称已存在", ResultCode.PARAM_ERROR);
            }
            if(!labelService.addDeviceLabel(labelAddRequest, null)){
                log.error("addDefault device labelName fail, labelAddRequest:{}", labelAddRequest);
                return BaseResponse.error("添加失败", ResultCode.SYSTEM_ERROR);
            }
        }else if(labelAddRequest.getType()==1){
            SaasSpaceLabel saasSpaceLabel =  labelService.querySpaceLabelByName(labelAddRequest.getLabelName(), null);
            if(saasSpaceLabel!=null){
                log.error("addDefault space labelName is exist, labelAddRequest:{}", labelAddRequest);
                return BaseResponse.error("标签名称已存在", ResultCode.PARAM_ERROR);
            }
            if(!labelService.addSpaceLabel(labelAddRequest, null)){
                log.error("addDefault space labelName fail, labelAddRequest:{}", labelAddRequest);
                return BaseResponse.error("添加失败", ResultCode.SYSTEM_ERROR);
            }
        }else {
            log.error("addDefault type is error, labelAddRequest:{}", labelAddRequest);
            return BaseResponse.error("标签类型不正确", ResultCode.PARAM_ERROR);
        }
        return BaseResponse.ok();
    }
    @PostMapping("/addCustom")
    public BaseResponse addCustom(HttpServletRequest request,  @RequestBody LabelAddRequest labelAddRequest){
        log.info("addCustom:{}", labelAddRequest);
        String token = request.getHeader("token");
        String customerId = JwtUtils.getCustomerId(token);
        if(StringUtils.isEmpty(labelAddRequest.getLabelName())){
            log.error("add labelName is null, labelAddRequest:{}", labelAddRequest);
            return BaseResponse.error("标签名称不能为空", ResultCode.PARAM_ERROR);
        }

        if(labelAddRequest.getType()==null) {
            log.error("add type is null, labelAddRequest:{}", labelAddRequest);
            return BaseResponse.error("标签类型不能为空", ResultCode.PARAM_ERROR);
        }
        List<String> roles = JwtUtils.getRole(token);
        if (!roles.contains(Constants.CUSTOMER_USER)){
            log.error("add no permission, labelAddRequest:{}", labelAddRequest);
            return BaseResponse.error("没有权限", ResultCode.PARAM_ERROR);
        }
        if(labelAddRequest.getType()==2){
            SaasDeviceLabel saasDeviceLabel = labelService.queryDeviceLabelByName(labelAddRequest.getLabelName(), customerId);
            if(saasDeviceLabel!=null){
                log.error("add device labelName is exist, labelAddRequest:{}", labelAddRequest);
                return BaseResponse.error("标签名称已存在", ResultCode.PARAM_ERROR);
            }
            if(!labelService.addDeviceLabel(labelAddRequest, customerId)){
                log.error("add device labelName fail, labelAddRequest:{}", labelAddRequest);
                return BaseResponse.error("添加失败", ResultCode.SYSTEM_ERROR);
            }
        }else if(labelAddRequest.getType()==1){
            SaasSpaceLabel saasSpaceLabel =  labelService.querySpaceLabelByName(labelAddRequest.getLabelName(), customerId);
            if(saasSpaceLabel!=null){
                log.error("add space labelName is exist, labelAddRequest:{}", labelAddRequest);
                return BaseResponse.error("标签名称已存在", ResultCode.PARAM_ERROR);
            }
            if(!labelService.addSpaceLabel(labelAddRequest, customerId)){
                log.error("add space labelName fail, labelAddRequest:{}", labelAddRequest);
                return BaseResponse.error("添加失败", ResultCode.SYSTEM_ERROR);
            }
        }else {
            log.error("add type is error, labelAddRequest:{}", labelAddRequest);
            return BaseResponse.error("标签类型不正确", ResultCode.PARAM_ERROR);
        }
        return BaseResponse.ok();
    }

    @PostMapping("/delete")
    public BaseResponse delete(HttpServletRequest request, @RequestBody LabelDeleteRequest labelDeleteRequest){
        log.info("delete labelDeleteRequest:{}", labelDeleteRequest);
        String token = request.getHeader("token");
        String customerId = JwtUtils.getCustomerId(token);
        if (labelDeleteRequest.getType()==null){
            log.error("delete type is null, labelDeleteRequest:{}", labelDeleteRequest);
            return BaseResponse.error("标签类型不能为空", ResultCode.PARAM_ERROR);
        }
        if(labelDeleteRequest.getId()==null){
            log.error("delete id is null, labelDeleteRequest:{}", labelDeleteRequest);
            return BaseResponse.error("标签ID不能为空", ResultCode.PARAM_ERROR);
        }
        List<String> roles = JwtUtils.getRole(token);
        if(labelDeleteRequest.getType()==1){
            SaasSpaceLabel saasSpaceLabel = labelService.getSpaceLabelById(labelDeleteRequest.getId());
            if(saasSpaceLabel==null){
                log.error("delete space label is not exist, labelDeleteRequest:{}", labelDeleteRequest);
                return BaseResponse.error("标签不存在", ResultCode.PARAM_ERROR);
            }
            List<SaasDeviceLabelRelation> saasDeviceLabelRelations = labelService.getDevicesBySpaceLabelId(labelDeleteRequest.getId());
            if(!CollectionUtils.isEmpty(saasDeviceLabelRelations)){
                log.error("delete space label has device, labelDeleteRequest:{}", labelDeleteRequest);
                return BaseResponse.error("空间标签下存在设备，请先删除设备", ResultCode.PARAM_ERROR);
            }
            if(saasSpaceLabel.getType()==0){
                if(!roles.contains(Constants.SYSTEM_ADMIN)){
                    log.error("delete space label no permission, labelDeleteRequest:{}", labelDeleteRequest);
                    return BaseResponse.error("用户没有权限", ResultCode.PARAM_ERROR);
                }
            }else {
                if(!roles.contains(Constants.TENANT_ADMIN) && !saasSpaceLabel.getCustomerId().equals(customerId)){
                    log.error("delete space label no permission, labelDeleteRequest:{}", labelDeleteRequest);
                    return BaseResponse.error("用户没有权限", ResultCode.PARAM_ERROR);
                }
            }
            if(!labelService.deleteSpaceLabel(labelDeleteRequest.getId())){
                log.error("delete space label fail, labelDeleteRequest:{}", labelDeleteRequest);
                return BaseResponse.error("删除失败", ResultCode.SYSTEM_ERROR);
            }
        }else if(labelDeleteRequest.getType()==2){
            SaasDeviceLabel saasDeviceLabel = labelService.getDeviceLabelById(labelDeleteRequest.getId());
            if(saasDeviceLabel==null){
                log.error("delete device label is not exist, labelDeleteRequest:{}", labelDeleteRequest);
                return BaseResponse.error("标签不存在", ResultCode.PARAM_ERROR);
            }
            List<SaasDeviceLabelRelation> saasDeviceLabelRelations = labelService.getDevicesByLabelId(labelDeleteRequest.getId());
            if(!CollectionUtils.isEmpty(saasDeviceLabelRelations)){
                log.error("delete device label has device, labelDeleteRequest:{}", labelDeleteRequest);
                return BaseResponse.error("设备标签下存在设备，请先删除设备", ResultCode.PARAM_ERROR);
            }

            if(StringUtils.isEmpty(saasDeviceLabel.getCustomerId())){
                if(!roles.contains(Constants.SYSTEM_ADMIN)){
                    log.error("delete device label no permission, labelDeleteRequest:{}", labelDeleteRequest);
                    return BaseResponse.error("用户没有权限", ResultCode.PARAM_ERROR);
                }
            }else {
                if(!roles.contains(Constants.TENANT_ADMIN) && !saasDeviceLabel.getCustomerId().equals(customerId)){
                    log.error("delete device label no permission, labelDeleteRequest:{}", labelDeleteRequest);
                    return BaseResponse.error("用户没有权限", ResultCode.PARAM_ERROR);
                }
            }

            if(!labelService.deleteDeviceLabel(labelDeleteRequest.getId())){
                log.error("delete device label fail, labelDeleteRequest:{}", labelDeleteRequest);
                return BaseResponse.error("删除失败", ResultCode.SYSTEM_ERROR);
            }
        }else {
            log.error("delete type is error, labelDeleteRequest:{}", labelDeleteRequest);
            return BaseResponse.error("标签类型不正确", ResultCode.PARAM_ERROR);
        }
        return BaseResponse.ok();
    }
}

